//// src/main/java/com/example/controller/CertificateController.java
//package wsdc.app.main.v1;
//
//
//import lombok.Data;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.io.FileSystemResource;
//import org.springframework.core.io.Resource;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.*;
//
//import java.io.File;
//import java.security.cert.X509Certificate;
//import java.util.*;
//
//@RestController
//@RequestMapping("/api/cert")
//public class CertificateControllerBark {
//
//    @Autowired
//    private CertificateService certificateService;
//
//    /**
//     * 1. 生成CA证书
//     */
//    @PostMapping("/ca")
//    public ResponseEntity<Map<String, Object>> generateCACertificate(@RequestBody CertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            //CertificateService.CertificateBundle caBundle = certificateService.generateCACertificate(request.getCommonName(), request.getOrganization(), request.getCountry(), request.getValidityYears());
//
//            CertificateService.CertificateBundle caBundle = certificateService.generateAndroidCompatibleCACertificate(request.getCommonName(), request.getOrganization(), request.getCountry(), request.getValidityYears());
//            // 保存为文件
//            certificateService.saveCertificateAsPEM(caBundle.getCertificate(), "ca-cert.pem");
//            certificateService.savePrivateKeyAsPEM(caBundle.getPrivateKey(), "ca-key.pem");
//
//            response.put("success", true);
//            response.put("message", "CA证书生成成功");
//            response.put("certificateFile", "ca-cert.pem");
//            response.put("keyFile", "ca-key.pem");
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("success", false);
//            response.put("message", "CA证书生成失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//
//
//    /**
//     * 导出CA根证书为CRT格式（用于浏览器信任）
//     */
//    @PostMapping("/export-ca-crt")
//    public ResponseEntity<Map<String, Object>> exportCACertificateAsCRT() {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            // 保存CA证书为CRT格式
//            certificateService.saveCertificateAsCRT(caBundle.getCertificate(), "ca-root-cert.crt");
//
//            response.put("success", true);
//            response.put("message", "CA根证书导出成功");
//            response.put("crtFile", "certs/ca-root-cert.crt");
//            response.put("downloadUrl", "/api/cert/download/ca-root-cert.crt");
//            response.put("instructions", "1. 下载 ca-root-cert.crt 文件\n" + "2. 将其导入到浏览器或操作系统的受信任根证书颁发机构中");
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "CA根证书导出失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 导出Android兼容的CA证书（多种格式）
//     */
//    @PostMapping("/export-ca-android")
//    public ResponseEntity<Map<String, Object>> exportAndroidCACertificate() {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            // 生成Android兼容的证书文件
//            certificateService.generateAndroidCACertificate(caBundle);
//
//            response.put("success", true);
//            response.put("message", "Android兼容的CA证书导出成功");
//            response.put("files", new String[]{"certs/ca-cert-android.pem", "certs/ca-cert-android.crt", "certs/ca-cert-android.cer", "certs/ca-cert-android.cer.crt"});
//            response.put("downloadUrls", new String[]{"/api/cert/download/ca-cert-android.pem", "/api/cert/download/ca-cert-android.crt", "/api/cert/download/ca-cert-android.cer", "/api/cert/download/ca-cert-android.cer.crt"});
//            response.put("instructions", "Android安装说明：\n" + "1. 下载 ca-cert-android.cer 或 ca-cert-android.crt 文件\n" + "2. 通过邮件、云存储或USB传输到Android设备\n" + "3. 在Android设备上打开文件进行安装\n" + "4. 根据Android版本选择安装到'用户证书'或'VPN和应用'");
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("success", false);
//            response.put("message", "Android兼容CA证书导出失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 验证CA证书是否适合移动设备使用
//     */
//    @PostMapping("/validate-mobile-ca")
//    public ResponseEntity<Map<String, Object>> validateMobileCACertificate() {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//            X509Certificate caCert = caBundle.getCertificate();
//
//            // 检查证书属性
//            response.put("success", true);
//            response.put("subject", caCert.getSubjectDN().toString());
//            response.put("issuer", caCert.getIssuerDN().toString());
//            response.put("notBefore", caCert.getNotBefore());
//            response.put("notAfter", caCert.getNotAfter());
//            response.put("signatureAlgorithm", caCert.getSigAlgName());
//            response.put("keyUsage", caCert.getKeyUsage());
//            response.put("basicConstraints", caCert.getBasicConstraints());
//
//            // 检查是否为CA证书
//            boolean isCA = caCert.getBasicConstraints() >= 0;
//            response.put("isCA", isCA);
//
//            // 检查密钥用法
//            boolean[] keyUsage = caCert.getKeyUsage();
//            boolean canSignCertificates = keyUsage != null && keyUsage[5]; // keyCertSign
//            response.put("canSignCertificates", canSignCertificates);
//
//            response.put("suitableForMobile", isCA && canSignCertificates);
//            response.put("validationNotes", isCA && canSignCertificates ? "证书适合作为移动设备的CA证书" : "证书可能不适合作为移动设备的CA证书，请重新生成");
//
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "CA证书验证失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//
//    /**
//     * 验证证书状态
//     */
//    @GetMapping("/cert-status")
//    public ResponseEntity<Map<String, Object>> getCertificateStatus() {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 检查CA证书文件是否存在
//            File caCertFile = new File("d:/cert/certs/ca-cert.pem");
//            File caKeyFile = new File("d:/cert/certs/ca-key.pem");
//
//            // 检查SSL证书文件是否存在
//            File sslCertFile = new File("d:/cert/certs/tomcat-ssl.p12");
//
//            response.put("success", true);
//            response.put("caCertificateExists", caCertFile.exists() && caKeyFile.exists());
//            response.put("sslCertificateExists", sslCertFile.exists());
//            response.put("caCertPath", caCertFile.getAbsolutePath());
//            response.put("caKeyPath", caKeyFile.getAbsolutePath());
//            response.put("sslCertPath", sslCertFile.getAbsolutePath());
//
//            if (caCertFile.exists() && caKeyFile.exists()) {
//                CertificateService.CertificateBundle caBundle = createSampleCABundle();
//                response.put("caSubject", caBundle.getCertificate().getSubjectDN().toString());
//                response.put("caNotAfter", caBundle.getCertificate().getNotAfter());
//            }
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "检查证书状态失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//
//    /**
//     * 3. 根据CA证书生成SSL证书
//     */
//    @PostMapping("/ssl")
//    public ResponseEntity<Map<String, Object>> generateSSLCertificate(@RequestBody SSLCertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 这里需要读取已有的CA证书和私钥
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            CertificateService.CertificateBundle sslBundle = certificateService.generateSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getValidityYears());
//
//            // 保存为文件
//            certificateService.saveCertificateAsPEM(sslBundle.getCertificate(), "ssl-cert.pem");
//            certificateService.savePrivateKeyAsPEM(sslBundle.getPrivateKey(), "ssl-key.pem");
//            certificateService.saveAsPKCS12(sslBundle.getCertificate(), sslBundle.getPrivateKey(), "ssl-cert.p12", request.getPassword());
//
//            response.put("success", true);
//            response.put("message", "SSL证书生成成功");
//            response.put("certificateFile", "ssl-cert.pem");
//            response.put("keyFile", "ssl-key.pem");
//            response.put("pkcs12File", "ssl-cert.p12");
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("success", false);
//            response.put("message", "SSL证书生成失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 3. 根据CA证书生成SSL证书（用于Tomcat）
//     */
//    @PostMapping("/ssl-tomcat-single")
//    public ResponseEntity<Map<String, Object>> generateTomcatSSLCertificate0(@RequestBody(required = false) SSLCertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 设置默认值
//            if (request == null) {
//                request = new SSLCertificateRequest();
//                request.setCommonName("localhost");
//                request.setOrganization("My Organization");
//                request.setCountry("CN");
//                request.setValidityYears(2);
//                request.setSanDomains(new String[]{"localhost", "127.0.0.1"});
//                request.setPassword("certpass123");
//            } else {
//                if (request.getCommonName() == null) request.setCommonName("localhost");
//                if (request.getOrganization() == null) request.setOrganization("My Organization");
//                if (request.getCountry() == null) request.setCountry("CN");
//                if (request.getValidityYears() <= 0) request.setValidityYears(2);
//                if (request.getSanDomains() == null) request.setSanDomains(new String[]{"localhost", "127.0.0.1"});
//                if (request.getPassword() == null || request.getPassword().isEmpty()) request.setPassword("changeit");
//            }
//
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            // 生成用于Tomcat的SSL证书
//            CertificateService.CertificateBundle sslBundle = certificateService.generateTomcatSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getValidityYears(), request.getPassword());
//
//            response.put("success", true);
//            response.put("message", "Tomcat SSL证书生成成功");
//            response.put("keystoreFile", "certs/tomcat-ssl.p12");
//            response.put("keystorePassword", request.getPassword());
//            response.put("instructions", "在application.properties中添加以下配置：\n" + "server.port=8443\n" + "server.ssl.enabled=true\n" + "server.ssl.key-store=certs/tomcat-ssl.p12\n" + "server.ssl.key-store-password=" + request.getPassword() + "\n" + "server.ssl.key-store-type=PKCS12\n" + "server.ssl.key-alias=key");
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("success", false);
//            response.put("message", "Tomcat SSL证书生成失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 生成支持泛域名的Tomcat SSL证书
//     */
//    @PostMapping("/tomcat-ssl-wildcard")
//    public ResponseEntity<Map<String, Object>> generateWildcardSSLCertificate1(@RequestBody(required = false) WildcardSSLCertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 设置默认值
//            if (request == null) {
//                request = new WildcardSSLCertificateRequest();
//            }
//
//            // 设置默认参数
//            if (request.getCommonName() == null) request.setCommonName("*.example.com");
//            if (request.getOrganization() == null) request.setOrganization("My Organization");
//            if (request.getCountry() == null) request.setCountry("CN");
//            if (request.getValidityYears() <= 0) request.setValidityYears(2);
//            if (request.getPassword() == null || request.getPassword().isEmpty()) request.setPassword("certpass123");
//
//            // 如果没有指定SAN域名，默认添加一些常用域名
//            if (request.getSanDomains() == null) {
//                request.setSanDomains(new String[]{"localhost", "127.0.0.1"});
//            }
//
//            // 如果没有指定泛域名，但Common Name是通配符，则使用Common Name
//            if (request.getWildcardDomain() == null || request.getWildcardDomain().isEmpty()) {
//                if (request.getCommonName().startsWith("*.")) {
//                    request.setWildcardDomain(request.getCommonName());
//                } else {
//                    request.setWildcardDomain("*." + request.getCommonName());
//                }
//            }
//
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            // 生成支持泛域名的SSL证书
//            CertificateService.CertificateBundle sslBundle = certificateService.generateWildcardSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getWildcardDomain(), request.getValidityYears(), request.getPassword());
//
//            // 保存为PKCS12格式文件（Tomcat可以直接使用）
//            certificateService.saveAsPKCS12(sslBundle.getCertificate(), sslBundle.getPrivateKey(), "wildcard-ssl.p12", request.getPassword());
//
//            response.put("success", true);
//            response.put("message", "泛域名SSL证书生成成功");
//            response.put("keystoreFile", "certs/wildcard-ssl.p12");
//            response.put("keystorePassword", request.getPassword());
//            response.put("commonName", request.getCommonName());
//            response.put("wildcardDomain", request.getWildcardDomain());
//            response.put("sanDomains", request.getSanDomains() != null ? request.getSanDomains() : new String[0]);
//            response.put("instructions", "在application.properties中添加以下配置：\n" + "server.port=8443\n" + "server.ssl.enabled=true\n" + "server.ssl.key-store=certs/wildcard-ssl.p12\n" + "server.ssl.key-store-password=" + request.getPassword() + "\n" + "server.ssl.key-store-type=PKCS12\n" + "server.ssl.key-alias=key");
//            response.put("usage", "此证书支持以下域名模式：\n" + "1. " + request.getCommonName() + "\n" + "2. " + request.getWildcardDomain() + " (泛域名)\n" + (request.getSanDomains() != null ? "3. SAN域名: " + String.join(", ", request.getSanDomains()) : ""));
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "泛域名SSL证书生成失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 3. 根据CA证书生成SSL证书（用于Tomcat）
//     */
//    @PostMapping("/ssl-tomcat")
//    public ResponseEntity<Map<String, Object>> generateTomcatSSLCertificate(@RequestBody(required = false) SSLCertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 设置默认值
//            if (request == null) {
//                request = new SSLCertificateRequest();
//                request.setCommonName("localhost");
//                request.setOrganization("My Organization");
//                request.setCountry("CN");
//                request.setValidityYears(2);
//                request.setSanDomains(new String[]{"localhost", "127.0.0.1"});
//                request.setPassword("certpass123");
//            } else {
//                if (request.getCommonName() == null) request.setCommonName("localhost");
//                if (request.getOrganization() == null) request.setOrganization("My Organization");
//                if (request.getCountry() == null) request.setCountry("CN");
//                if (request.getValidityYears() <= 0) request.setValidityYears(2);
//                if (request.getSanDomains() == null) request.setSanDomains(new String[]{"localhost", "127.0.0.1"});
//                if (request.getPassword() == null || request.getPassword().isEmpty()) request.setPassword("changeit");
//            }
//
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            CertificateService.CertificateBundle sslBundle;
//
//            // 检查是否需要生成泛域名证书
//            if (request.getCommonName().startsWith("*.")) {
//                // 生成泛域名证书
//                sslBundle = certificateService.generateWildcardSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getCommonName(), // 使用Common Name作为泛域名
//                        request.getValidityYears(), request.getPassword());
//            } else {
//                // 生成普通SSL证书
//                sslBundle = certificateService.generateTomcatSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), request.getSanDomains(), request.getValidityYears(), request.getPassword());
//            }
//
//            response.put("success", true);
//            response.put("message", "Tomcat SSL证书生成成功");
//            response.put("keystoreFile", "certs/tomcat-ssl.p12");
//            response.put("keystorePassword", request.getPassword());
//            response.put("isWildcard", request.getCommonName().startsWith("*."));
//            response.put("instructions", "在application.properties中添加以下配置：\n" + "server.port=8443\n" + "server.ssl.enabled=true\n" + "server.ssl.key-store=certs/tomcat-ssl.p12\n" + "server.ssl.key-store-password=" + request.getPassword() + "\n" + "server.ssl.key-store-type=PKCS12\n" + "server.ssl.key-alias=key");
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.put("success", false);
//            response.put("message", "Tomcat SSL证书生成失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//
//    /**
//     * 下载证书文件
//     */
//    @GetMapping("/download/{filename}")
//    public ResponseEntity<Resource> downloadCertificate(@PathVariable String filename) {
//        try {
//            File file = new File("D:\\cert\\certs\\" + filename);
//            if (!file.exists()) {
//                return ResponseEntity.notFound().build();
//            }
//
//            FileSystemResource resource = new FileSystemResource(file);
//            HttpHeaders headers = new HttpHeaders();
//            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
//
//            return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
//        } catch (Exception e) {
//            return ResponseEntity.internalServerError().build();
//        }
//    }
//
//
//    // 修改 createSampleCABundle 方法
//    private CertificateService.CertificateBundle createSampleCABundle() throws Exception {
//        File certFile = new File("d:/cert/certs/ca-cert.pem");
//        File keyFile = new File("d:/cert/certs/ca-key.pem");
//
//        // 如果文件存在，则从文件加载CA证书
//        if (certFile.exists() && keyFile.exists()) {
//            return certificateService.loadCACertificateFromDisk("d:/cert/certs/ca-cert.pem", "d:/cert/certs/ca-key.pem");
//        }
//        return null;
//    }
//
//    /**
//     * 生成Nginx SSL证书
//     */
//    @PostMapping("/nginx-ssl")
//    public ResponseEntity<Map<String, Object>> generateNginxSSLCertificate(@RequestBody(required = false) NginxSSLCertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 设置默认值
//            if (request == null) {
//                request = new NginxSSLCertificateRequest();
//            }
//
//            // 设置默认参数
//            if (request.getCommonName() == null) request.setCommonName("example.com");
//            if (request.getOrganization() == null) request.setOrganization("My Organization");
//            if (request.getCountry() == null) request.setCountry("CN");
//            if (request.getValidityYears() <= 0) request.setValidityYears(2);
//
//            // 确保至少有一个域名
//            List<String> allDomains = new ArrayList<>();
//            if (request.getSanDomains() != null) {
//                allDomains.addAll(Arrays.asList(request.getSanDomains()));
//            }
//
//            // 确保Common Name也在域名列表中
//            if (!allDomains.contains(request.getCommonName())) {
//                allDomains.add(0, request.getCommonName());
//            }
//
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            // 生成Nginx SSL证书
//            CertificateService.NginxSSLCertificateBundle nginxCertBundle = certificateService.generateNginxSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), allDomains.toArray(new String[0]), request.getValidityYears());
//
//            // 创建包含CA证书的完整证书包
//            CertificateService.NginxSSLCertificateBundle fullCertBundle = new CertificateService.NginxSSLCertificateBundle(nginxCertBundle.getCertificate(), nginxCertBundle.getPrivateKey(), caBundle.getCertificate());
//
//            // 生成域名安全的目录名
//            String domainName = request.getCommonName().replaceAll("[^a-zA-Z0-9.-]", "_");
//
//            // 保存Nginx证书文件
//            certificateService.saveNginxSSLCertificate(fullCertBundle, domainName);
//
//            response.put("success", true);
//            response.put("message", "Nginx SSL证书生成成功");
//            response.put("domain", request.getCommonName());
//            response.put("certificatePath", "certs/nginx/" + domainName + "/" + domainName + ".crt");
//            response.put("privateKeyPath", "certs/nginx/" + domainName + "/" + domainName + ".key");
//            response.put("certificateChainPath", "certs/nginx/" + domainName + "/" + domainName + "-chain.crt");
//            response.put("fullPemPath", "certs/nginx/" + domainName + "/" + domainName + "-full.pem");
//            response.put("domains", allDomains);
//            response.put("nginxConfigExample", generateNginxConfigExample(domainName, request.getCommonName()));
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "Nginx SSL证书生成失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 生成Nginx配置示例
//     */
//    private String generateNginxConfigExample(String domainName, String commonName) {
//        return "# Nginx SSL配置示例\n" + "server {\n" + "    listen 443 ssl;\n" + "    server_name " + commonName + ";\n\n" + "    ssl_certificate /path/to/certs/nginx/" + domainName + "/" + domainName + ".crt;\n" + "    ssl_certificate_key /path/to/certs/nginx/" + domainName + "/" + domainName + ".key;\n" + "    ssl_protocols TLSv1.2 TLSv1.3;\n" + "    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;\n" + "    ssl_prefer_server_ciphers off;\n\n" + "    location / {\n" + "        # 您的应用配置\n" + "    }\n" + "}\n\n" + "# HTTP重定向到HTTPS\n" + "server {\n" + "    listen 80;\n" + "    server_name " + commonName + ";\n" + "    return 301 https://$server_name$request_uri;\n" + "}";
//    }
//
//    /**
//     * 列出所有Nginx证书
//     */
//    @GetMapping("/nginx-ssl/list")
//    public ResponseEntity<Map<String, Object>> listNginxCertificates() {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            File nginxCertDir = new File("d:/cert/certs/nginx");
//            if (!nginxCertDir.exists()) {
//                response.put("success", true);
//                response.put("certificates", new String[0]);
//                response.put("message", "Nginx证书目录不存在");
//                return ResponseEntity.ok(response);
//            }
//
//            File[] domainDirs = nginxCertDir.listFiles(File::isDirectory);
//            List<Map<String, Object>> certificates = new ArrayList<>();
//
//            if (domainDirs != null) {
//                for (File domainDir : domainDirs) {
//                    Map<String, Object> certInfo = new HashMap<>();
//                    certInfo.put("domain", domainDir.getName());
//                    certInfo.put("path", domainDir.getAbsolutePath());
//
//                    // 检查证书文件是否存在
//                    File certFile = new File(domainDir, domainDir.getName() + ".crt");
//                    File keyFile = new File(domainDir, domainDir.getName() + ".key");
//                    File chainFile = new File(domainDir, domainDir.getName() + "-chain.crt");
//
//                    certInfo.put("certificateExists", certFile.exists());
//                    certInfo.put("privateKeyExists", keyFile.exists());
//                    certInfo.put("chainExists", chainFile.exists());
//                    certInfo.put("lastModified", domainDir.lastModified());
//
//                    if (certFile.exists()) {
//                        certInfo.put("certificateSize", certFile.length());
//                    }
//
//                    certificates.add(certInfo);
//                }
//            }
//
//            response.put("success", true);
//            response.put("certificates", certificates);
//            response.put("count", certificates.size());
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "列出Nginx证书失败: " + e.getMessage());
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 下载Nginx证书文件
//     */
//    @GetMapping("/nginx-ssl/download/{domain}/{filename}")
//    public ResponseEntity<Resource> downloadNginxCertificate(@PathVariable String domain, @PathVariable String filename) {
//        try {
//            File file = new File("d:/cert/certs/nginx/" + domain + "/" + filename);
//            if (!file.exists()) {
//                return ResponseEntity.notFound().build();
//            }
//
//            FileSystemResource resource = new FileSystemResource(file);
//            HttpHeaders headers = new HttpHeaders();
//            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);
//
//            return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).body(resource);
//        } catch (Exception e) {
//            return ResponseEntity.internalServerError().build();
//        }
//    }
//
//    /**
//     * 生成Nginx泛域名SSL证书
//     */
//    @PostMapping("/nginx-ssl-wildcard")
//    public ResponseEntity<Map<String, Object>> generateNginxWildcardSSLCertificate(@RequestBody(required = false) NginxWildcardSSLCertificateRequest request) {
//        Map<String, Object> response = new HashMap<>();
//        try {
//            // 设置默认值
//            if (request == null) {
//                request = new NginxWildcardSSLCertificateRequest();
//            }
//
//            // 设置默认参数
//            if (request.getCommonName() == null) request.setCommonName("*.example.com");
//            if (request.getOrganization() == null) request.setOrganization("My Organization");
//            if (request.getCountry() == null) request.setCountry("CN");
//            if (request.getValidityYears() <= 0) request.setValidityYears(2);
//
//            // 构建SAN域名列表
//            List<String> sanDomains = new ArrayList<>();
//            sanDomains.add(request.getCommonName()); // 泛域名
//
//            // 添加根域名（如果未包含）
//            String rootDomain = request.getCommonName().substring(2); // 移除 "*."
//            if (!sanDomains.contains(rootDomain)) {
//                sanDomains.add(rootDomain);
//            }
//
//            // 添加其他SAN域名
//            if (request.getAdditionalDomains() != null) {
//                sanDomains.addAll(Arrays.asList(request.getAdditionalDomains()));
//            }
//
//            // 获取CA证书
//            CertificateService.CertificateBundle caBundle = createSampleCABundle();
//
//            // 生成Nginx SSL证书
//            CertificateService.NginxSSLCertificateBundle nginxCertBundle = certificateService.generateNginxSSLCertificate(caBundle, request.getCommonName(), request.getOrganization(), request.getCountry(), sanDomains.toArray(new String[0]), request.getValidityYears());
//
//            // 创建包含CA证书的完整证书包
//            CertificateService.NginxSSLCertificateBundle fullCertBundle = new CertificateService.NginxSSLCertificateBundle(nginxCertBundle.getCertificate(), nginxCertBundle.getPrivateKey(), caBundle.getCertificate());
//
//            // 生成域名安全的目录名
//            String domainName = request.getCommonName().replaceAll("[^a-zA-Z0-9.-]", "_");
//
//            // 保存Nginx证书文件
//            certificateService.saveNginxSSLCertificate(fullCertBundle, domainName);
//
//            response.put("success", true);
//            response.put("message", "Nginx泛域名SSL证书生成成功");
//            response.put("domain", request.getCommonName());
//            response.put("certificatePath", "certs/nginx/" + domainName + "/" + domainName + ".crt");
//            response.put("privateKeyPath", "certs/nginx/" + domainName + "/" + domainName + ".key");
//            response.put("certificateChainPath", "certs/nginx/" + domainName + "/" + domainName + "-chain.crt");
//            response.put("fullPemPath", "certs/nginx/" + domainName + "/" + domainName + "-full.pem");
//            response.put("domains", sanDomains);
//            response.put("nginxConfigExample", generateNginxWildcardConfigExample(domainName, request.getCommonName(), rootDomain));
//        } catch (Exception e) {
//            response.put("success", false);
//            response.put("message", "Nginx泛域名SSL证书生成失败: " + e.getMessage());
//            e.printStackTrace();
//        }
//        return ResponseEntity.ok(response);
//    }
//
//    /**
//     * 生成Nginx泛域名配置示例
//     */
//    private String generateNginxWildcardConfigExample(String domainName, String wildcardDomain, String rootDomain) {
//        return "# Nginx泛域名SSL配置示例\n" + "server {\n" + "    listen 443 ssl;\n" + "    server_name " + wildcardDomain + " " + rootDomain + ";\n\n" + "    ssl_certificate /path/to/certs/nginx/" + domainName + "/" + domainName + ".crt;\n" + "    ssl_certificate_key /path/to/certs/nginx/" + domainName + "/" + domainName + ".key;\n" + "    ssl_protocols TLSv1.2 TLSv1.3;\n" + "    ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512;\n" + "    ssl_prefer_server_ciphers off;\n\n" + "    location / {\n" + "        # 您的应用配置\n" + "    }\n" + "}\n\n" + "# HTTP重定向到HTTPS\n" + "server {\n" + "    listen 80;\n" + "    server_name " + wildcardDomain + " " + rootDomain + ";\n" + "    return 301 https://$server_name$request_uri;\n" + "}";
//    }
//
//    @Data
//    class NginxWildcardSSLCertificateRequest {
//        private String commonName = "*.example.com";     // 泛域名
//        private String organization = "My Organization"; // 组织名称
//        private String country = "CN";                   // 国家代码
//        private int validityYears = 2;                   // 有效期（年）
//        private String[] additionalDomains;              // 额外的SAN域名
//    }
//
//
//}
